package com.ruoyi.bizsys.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Arrays;

import com.ruoyi.bizsys.domain.*;
import com.ruoyi.bizsys.mapper.*;
import com.ruoyi.bizsys.utils.BizConstants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.bizsys.service.ILoanOffsetService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;


/**
 * 借据冲账管理Service业务层处理
 *
 * @author african-loan
 * @date 2021-12-30
 */
@Service
public class LoanOffsetServiceImpl extends ServiceImpl<LoanOffsetMapper, LoanOffset> implements ILoanOffsetService {
    @Autowired
    RepaymentOrderMapper repaymentOrderMapper;

    @Autowired
    CustReduceOrderMapper custReduceOrderMapper;

    @Autowired
    AccountFlowMapper accountFlowMapper;

    @Autowired
    LoanIouMapper loanIouMapper;


    /**
     * 查询借据冲账管理
     *
     * @param id 借据冲账管理ID
     * @return 借据冲账管理
     */
    @Override
    public LoanOffset selectLoanOffsetById(Long id) {
        return this.getById(id);
    }

    /**
     * 查询借据冲账管理列表
     *
     * @param loanOffset 借据冲账管理
     * @return 借据冲账管理
     */
    @Override
    public List<LoanOffset> selectLoanOffsetList(LoanOffset loanOffset) {
        return this.list(new QueryWrapper<>(loanOffset).last("order by id desc"));
    }

    /**
     * 后台使用
     * @param loanOffset 借据冲账管理
     * @return
     */
    @Override
    public List<LoanOffset> getList(LoanOffset loanOffset) {
        if(loanOffset.getParams().entrySet().size() > 0){
            return this.list(new QueryWrapper<>(loanOffset).ge("create_time",loanOffset.getParams().get("beginTime")).lt("create_time",loanOffset.getParams().get("endTime")).last("order by id desc"));
        }
        return this.list(new QueryWrapper<>(loanOffset).last("order by id desc"));
    }

    /**
     * 新增借据冲账管理
     *
     * @param loanOffset 借据冲账管理
     * @return 结果
     */
    @Override
    public int insertLoanOffset(LoanOffset loanOffset) {
        loanOffset.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insert(loanOffset);
    }

    /**
     * 修改借据冲账管理
     *
     * @param loanOffset 借据冲账管理
     * @return 结果
     */
    @Override
    public int updateLoanOffset(LoanOffset loanOffset) {
        loanOffset.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateById(loanOffset);
    }

    /**
     * 批量删除借据冲账管理
     *
     * @param ids 需要删除的借据冲账管理ID
     * @return 结果
     */
    @Override
    public int deleteLoanOffsetByIds(Long[] ids) {
        return baseMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除借据冲账管理信息
     *
     * @param id 借据冲账管理ID
     * @return 结果
     */
    @Override
    public int deleteLoanOffsetById(Long id) {
        return baseMapper.deleteById(id);
    }

    /**
     * 取消优惠，更新offset 10 状态，custreduceOrder 10 去掉repayOrder减免和减免订单ID
     *
     * @param repaymentOrder
     * @param actionType
     */
    @Override
    @Transactional
    public void updateLoanOffsetAndRepayOrder(RepaymentOrder repaymentOrder, String actionType) {
        LoanOffset loanOffset = new LoanOffset();
        loanOffset.setCustNo(repaymentOrder.getCustNo());
        loanOffset.setLoanSerialNo(repaymentOrder.getLoanSerialNo());
        loanOffset.setActionType(actionType);
        loanOffset.setRepaymentNo(repaymentOrder.getRepaymentNo());
        loanOffset.setLoanOffsetStatus(10);// 取消优惠
        baseMapper.updateReduceOffsetStatus(loanOffset);

        CustReduceOrder custReduceOrder = new CustReduceOrder();
        custReduceOrder.setId(repaymentOrder.getCustReduceOrderId());
        custReduceOrder.setStatus(10);// 取消优惠
        custReduceOrderMapper.updateById(custReduceOrder);
        //删除减免信息
        repaymentOrderMapper.updateRepaymentOrderReomveReduceById(repaymentOrder);

    }

    @Override
    public List<LoanOffset> selectLoanOffsetListByLateFee() {
        return baseMapper.selectLoanOffsetListByLateFee();
    }


    private void updateAccountFlowStateFaild(LoanIou loanIou) {
        AccountFlow accountFlow = new AccountFlow();
        accountFlow.setCustNo(loanIou.getCustNo());
        accountFlow.setRelativeSerialNo(loanIou.getLoanSerialNo());
        accountFlowMapper.updateByIndex(accountFlow);
    }

    private LoanOffset createLoanOffsetSuccess(Date completedOn, RepaymentOrder repaymentOrder) {
        LoanOffset loanOffset = new LoanOffset();
        loanOffset.setCustNo(repaymentOrder.getCustNo());
        loanOffset.setLoanSerialNo(repaymentOrder.getLoanSerialNo());
        loanOffset.setRepaymentNo(repaymentOrder.getRepaymentNo());
        loanOffset.setActionType(repaymentOrder.getActionType());
        loanOffset.setAmt(repaymentOrder.getRepaymentAmt());
        loanOffset.setPayTime(completedOn);
        loanOffset.setLoanPrincipal(repaymentOrder.getLoanPrincipal());
        loanOffset.setRepaidPrincipal(repaymentOrder.getRepaidPrincipal());
        loanOffset.setServiceFee(repaymentOrder.getServiceFee());
        loanOffset.setRepaidServiceFee(repaymentOrder.getRepaidServiceFee());
        loanOffset.setLoanInterest(repaymentOrder.getLoanInterest());
        loanOffset.setRepaidInterest(repaymentOrder.getRepaidInterest());
        if (repaymentOrder.getLateFee() == null) {
            repaymentOrder.setLateFee(BigDecimal.ZERO);
        }
        if (repaymentOrder.getReduceFee() == null) {
            repaymentOrder.setReduceFee(BigDecimal.ZERO);
        }
        loanOffset.setLateFee(repaymentOrder.getLateFee());// 不需要 wqg沟通过 后期遇到延迟冲账的场景去回溯
        loanOffset.setRepaidLateFee(repaymentOrder.getRepaidLateFee());

        loanOffset.setLoanOffsetStatus(BizConstants.LOAN_OFFSET_STATUS_SUCCESS);
        loanOffset.setState(UserConstants.BUSINESS_NORMAL);
        baseMapper.insert(loanOffset);
        return loanOffset;
    }

    private RepaymentOrder createRepaymentOrder(LoanIou loanIou, String paymentReference, Date completedOn, BigDecimal amountPaid) {
        RepaymentOrder repaymentOrder = new RepaymentOrder();
        repaymentOrder.setRepaymentNo(IdUtils.reqId());
        repaymentOrder.setCustNo(loanIou.getCustNo());
        repaymentOrder.setLoanSerialNo(loanIou.getLoanSerialNo());

        repaymentOrder.setActionType(RepaymentOrder.ACTION_TYPE_FINANCE);

        BigDecimal needTotal = loanIou.getLoanPrincipal().add(loanIou.getLoanInterest()).add(loanIou.getServiceFee()).add(loanIou.getLateFee());
        BigDecimal repaidTotal = loanIou.getRepaidPrincipal().add(loanIou.getRepaidInterest()).add(loanIou.getRepaidServiceFee()).add(loanIou.getRepaidLateFee());
        // 计算减免金额
        BigDecimal reduceAmt = loanIou.getReduceAmt() == null ? BigDecimal.ZERO : loanIou.getReduceAmt();
        BigDecimal repaymentAmt = needTotal.subtract(repaidTotal).subtract(reduceAmt);
        if (null != amountPaid) {
            repaymentAmt = amountPaid;
        }
        if (repaymentAmt.compareTo(BigDecimal.ZERO) == 1) {//如果金额大于0
            repaymentOrder.setRepaymentAmt(repaymentAmt.setScale(0, BigDecimal.ROUND_UP));
        }
        repaymentOrder.setReduceFee(reduceAmt);

        repaymentOrder.setLoanPrincipal(loanIou.getLoanPrincipal().subtract(loanIou.getRepaidPrincipal()));
        repaymentOrder.setRepaidPrincipal(BigDecimal.ZERO);
        repaymentOrder.setServiceFee(loanIou.getServiceFee().subtract(loanIou.getRepaidServiceFee()));
        repaymentOrder.setRepaidServiceFee(BigDecimal.ZERO);
        repaymentOrder.setLoanInterest(loanIou.getLoanInterest().subtract(loanIou.getRepaidInterest()));
        repaymentOrder.setRepaidInterest(BigDecimal.ZERO);
        repaymentOrder.setLateFee(loanIou.getLateFee().subtract(loanIou.getRepaidLateFee()));
        repaymentOrder.setRepaidLateFee(BigDecimal.ZERO);

        repaymentOrder.setRepayStatus(BizConstants.REPAYMENT_ORDER_STATUS_SUCCESS);
        repaymentOrder.setPayTransSerialNo(paymentReference);

        repaymentOrder.setPayTime(completedOn);
        repaymentOrder.setState(UserConstants.BUSINESS_NORMAL);
        Date nowTime = new Date();
        repaymentOrder.setCreateTime(nowTime);
        repaymentOrder.setUpdateTime(nowTime);
        repaymentOrderMapper.insert(repaymentOrder);
        return repaymentOrder;
    }


}
